package com.example.student.web;

import com.example.student.service.UserService;
import com.example.student.service.factory.ServiceFactory;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Objects;

/**
 * @author TonySong
 * @date 2025/8/7 0007
 * @time 12:13
 */
public class BaseServlet extends HttpServlet {

    protected static final String PREFIX="/WEB-INF/view/";
    protected static final String  SUFFIX=".jsp";

    protected UserService userService= ServiceFactory.createUserService();
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         request.setCharacterEncoding("utf-8");
         response.setContentType("text/html;charset=utf-8");
         response.setCharacterEncoding("utf-8");
         String urlAnnotation=null;
         //获取请求的Servlet对象
        Class<?> servletClass = this.getClass();
        // 直接获取类上的WebServlet注解（用于拼接url）
        WebServlet servletAnnotation = servletClass.getAnnotation(WebServlet.class);
        if(servletAnnotation != null) {
          urlAnnotation =    servletAnnotation.value()[0];
            System.out.println(urlAnnotation);
        }
        /**
         * 1. 获取method参数，它是用户想调用的方法
         */
        String methodName = request.getParameter("action");
        System.out.println("请求的方法："+methodName);
        Method method=null;

        try {
            //2. 通过反射获取方法
            method = this.getClass().getDeclaredMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException("没有找到对应的方法");
        }

        /**
         *
         * 3. 通过method对象来调用它
         */
        try {
            String result = (String)method.invoke(this, request, response);
            System.out.println("方法的返回值是："+result);
            if(result != null && !result.trim().isEmpty()) {//如果请求处理方法返回不为空
                int index = result.indexOf(":");//获取第一个冒号的位置 f:login.jsp
                if(index == -1) {//如果没有冒号，使用转发
                    request.getRequestDispatcher(result).forward(request, response);
                } else {//如果存在冒号
                    String start = result.substring(0, index);//分割出前缀
                    String path = result.substring(index + 1);//分割出路径
                    System.out.println("start:"+start);
                    System.out.println("path:"+path);
                    if("forward".equals(start)) {//前缀为forward表示转发
                        request.getRequestDispatcher(path).forward(request, response);
                    } else if("redirect".equals(start)) {//前缀为redirect表示重定向
                        String contextPath=request.getContextPath()+urlAnnotation+"?action=";
                        System.out.println(contextPath);
                        System.out.println(path);
                        response.sendRedirect(contextPath + path);
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }
}
